package com.mtw.bbs.common.core.security.context.strategy;

import com.mtw.bbs.common.core.security.context.SecurityContext;
import com.mtw.bbs.common.core.security.context.SecurityContextHolderStrategy;
import com.mtw.bbs.common.core.security.context.SecurityContextImpl;
import org.springframework.util.Assert;

/**
 * 基于静态字段实现的上下文策略。JVM中的所有实例共享相同的SecurityContext。
 */
public class GlobalSecurityContextHolderStrategy implements SecurityContextHolderStrategy {

    private static SecurityContext contextHolder;


    /**
     * 清理
     */
    public void clearContext() {
        contextHolder = null;
    }


    /**
     * 获取
     */
    public SecurityContext getContext() {
        if (contextHolder == null) {
            contextHolder = new SecurityContextImpl();
        }

        return contextHolder;
    }



    /**
     * 设置
     */
    public void setContext(SecurityContext context) {
        Assert.notNull(context, "Only non-null SecurityContext instances are permitted");
        contextHolder = context;
    }


    /**
     * 创建一个空的上下文
     */
    public SecurityContext createEmptyContext() {
        return new SecurityContextImpl();
    }
}
